<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

use function PHPUnit\Framework\isEmpty;
use function PHPUnit\Framework\throwException;

class Role extends BaseModel
{
    use HasFactory;
    public $timestamps = false;
    protected $guarded = [];
    protected $table = 'sys_role';
    public function rolesList()
    {
        return $this->hasMany(RoleList::class, 'childrenrole_id', 'id');
    }
    public function saveitems($items)
    {
        $role_ids = $this->rolesList()->pluck('id', 'id')->toArray();
        foreach ($items as $v) {
        
            if (isset($v['id']) && (int)$v['id'] > 0) {
                if (isset($role_ids[$v['id']])) {
                    RoleList::where("id", $v['id'])->update($v);
                    unset($role_ids[$v['id']]);
                } else
                    throwError("保存角色所属时参数错误！");
            } else {
                $v['childrenrole_id'] = $this->id;

                if (!RoleList::where(["childrenrole_id" => $this->id, "role_id" => $v['role_id']])->exists())
                    RoleList::create(array_filter($v));
            }
        }
        //删除已经不存在的
        foreach (RoleList::whereIn("id", $role_ids)->get() as $v) {
            $v->delete();
        };
    }

    public function _deleting()
    {
        foreach ($this->rolesList()->get() as $k => $v) {
            $v->delete();
        }
    }
    public function scopeSearch($query, &$search)
    {
        if (isset($search['name']))
            $query->where('name', 'like', '%' . $search['name'] . '%');
        parent::scopeSearch($query, $search);
        return $query;
    }

    public function scopeRelatedJoin($query)
    {
    }
}
